import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class MusicPlay extends StatefulWidget {
  final String rid;
  const MusicPlay({Key key, this.rid}) : super(key: key);

  @override
  _MusicPlayState createState() => _MusicPlayState();
}

class _MusicPlayState extends State<MusicPlay> {

  AudioPlayer advancedPlayer = AudioPlayer();

  @override
  void initState() {
    super.initState();
    advancedPlayer.startHeadlessService();
    _playMusic();
  }

  void _playMusic() async {
    await http.get(
        'http://www.kuwo.cn/url?format=mp3&rid='+widget.rid+'&type=convert_url3&br=128kmp3',
        headers: {
          'Cookie': 'kw_token=7J23VNPXENR',
          'csrf': '7J23VNPXENR'
        }).then((http.Response response) {
      Map<String, dynamic> user = json.decode(response.body);
      if (user['code'] == 200) {
        advancedPlayer.play(user['url']);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.rid),
        actions: <Widget>[
          InkWell(
            child: Text('暂停'),
            onTap: (){
              advancedPlayer.pause();
            },
          ),
          SizedBox(
            width: 20,
          ),
          InkWell(
            child: Text('播放'),
            onTap: (){
              advancedPlayer.resume();
            },
          ),
        ],
      ),
    );
  }
}
